package com.donglu.handCardUsage;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.DateTime;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Text;


public class HandCardUsageApp {

	protected Shell shell;
	private Table table;
	private List<Device> allDevice;
	private Text txt_cardIdentifier;
	private Text txt_cardSeriNumber;
	private Text txt_userIdentifier;
	private Text txt_userName;
	private Table tb_card;
	private List<PhysicalCard> allCard;
	private DatabaseConfig config=new DatabaseConfig();
	private Map<String, PhysicalCard> mapCard;
	private DateTime dt_date;
	private DateTime dt_time;
	private DataService service;

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			HandCardUsageApp window = new HandCardUsageApp();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(955, 543);
		shell.setText("手动插入刷卡记录");
		shell.setLayout(new GridLayout(1, false));
		
		Composite composite = new Composite(shell, SWT.NONE);
		composite.setLayout(new GridLayout(5, false));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		dt_date = new DateTime(composite, SWT.BORDER);
		
		dt_time = new DateTime(composite, SWT.BORDER | SWT.TIME);
		
		Button button = new Button(composite, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				handCardUsage();
			}
		});
		button.setText("打卡");
		
		Button button_1 = new Button(composite, SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				refresh();
			}
		});
		button_1.setText("刷新数据");
		
		Button button_3 = new Button(composite, SWT.NONE);
		button_3.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				DatabaseConfigApp app = new DatabaseConfigApp(config);
				config=app.open();
			}
		});
		button_3.setText("配置");
		
		Composite composite_1 = new Composite(shell, SWT.NONE);
		composite_1.setLayout(new FillLayout(SWT.HORIZONTAL));
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		SashForm sashForm = new SashForm(composite_1, SWT.NONE);
		
		Composite composite_2 = new Composite(sashForm, SWT.NONE);
		composite_2.setLayout(new FillLayout(SWT.HORIZONTAL));
		
		table = new Table(composite_2, SWT.BORDER | SWT.FULL_SELECTION);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		
		TableColumn tableColumn = new TableColumn(table, SWT.NONE);
		tableColumn.setWidth(65);
		tableColumn.setText("设备编号");
		
		TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE);
		tableColumn_1.setWidth(75);
		tableColumn_1.setText("设备名称");
		
		TableColumn tableColumn_2 = new TableColumn(table, SWT.NONE);
		tableColumn_2.setWidth(65);
		tableColumn_2.setText("设备地址");
		
		TableColumn tableColumn_3 = new TableColumn(table, SWT.NONE);
		tableColumn_3.setWidth(100);
		tableColumn_3.setText("设备连接");
		
		
		
		Composite composite_3 = new Composite(sashForm, SWT.NONE);
		composite_3.setLayout(new GridLayout(1, false));
		
		Composite composite_4 = new Composite(composite_3, SWT.NONE);
		composite_4.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		composite_4.setLayout(new GridLayout(5, false));
		
		Label label = new Label(composite_4, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label.setText("卡片编号");
		
		txt_cardIdentifier = new Text(composite_4, SWT.BORDER);
		GridData gd_txt_cardIdentifier = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_txt_cardIdentifier.widthHint = 121;
		txt_cardIdentifier.setLayoutData(gd_txt_cardIdentifier);
		
		Label label_1 = new Label(composite_4, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_1.setText("卡片内码");
		
		txt_cardSeriNumber = new Text(composite_4, SWT.BORDER);
		GridData gd_txt_cardSeriNumber = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_txt_cardSeriNumber.widthHint = 144;
		txt_cardSeriNumber.setLayoutData(gd_txt_cardSeriNumber);
		new Label(composite_4, SWT.NONE);
		
		Label label_2 = new Label(composite_4, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_2.setText("用户编号");
		
		txt_userIdentifier = new Text(composite_4, SWT.BORDER);
		txt_userIdentifier.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		Label label_3 = new Label(composite_4, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_3.setText("用户姓名");
		
		txt_userName = new Text(composite_4, SWT.BORDER);
		txt_userName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		Button button_2 = new Button(composite_4, SWT.NONE);
		button_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				filterCard();
			}
		});
		button_2.setText("过滤");
		
		Composite composite_5 = new Composite(composite_3, SWT.NONE);
		composite_5.setLayout(new FillLayout(SWT.HORIZONTAL));
		composite_5.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		tb_card = new Table(composite_5, SWT.BORDER | SWT.FULL_SELECTION);
		tb_card.setHeaderVisible(true);
		tb_card.setLinesVisible(true);
		
		TableColumn tableColumn_4 = new TableColumn(tb_card, SWT.NONE);
		tableColumn_4.setWidth(100);
		tableColumn_4.setText("卡片编号");
		
		TableColumn tableColumn_5 = new TableColumn(tb_card, SWT.NONE);
		tableColumn_5.setWidth(100);
		tableColumn_5.setText("卡片内码");
		
		TableColumn tableColumn_6 = new TableColumn(tb_card, SWT.NONE);
		tableColumn_6.setWidth(100);
		tableColumn_6.setText("用户编号");
		
		TableColumn tableColumn_7 = new TableColumn(tb_card, SWT.NONE);
		tableColumn_7.setWidth(100);
		tableColumn_7.setText("用户姓名");
		
		TableColumn tableColumn_8 = new TableColumn(tb_card, SWT.NONE);
		tableColumn_8.setWidth(100);
		tableColumn_8.setText("用户组");
		sashForm.setWeights(new int[] {335, 591});
		init();
	}
	
	protected void handCardUsage() {
		int index = table.getSelectionIndex();
		System.out.println(index);
		TableItem[] items = tb_card.getSelection();
		if (index<0||items==null||items.length<=0) {
			info("请选择设备和卡片后再点打卡");
			return;
		}
		Device device = allDevice.get(index);
		PhysicalCard card = mapCard.get(items[0].getText(0));
		Calendar c = Calendar.getInstance();
		c.set(dt_date.getYear(), dt_date.getMonth(), dt_date.getDay(), dt_time.getHours(), dt_time.getMinutes(), dt_time.getSeconds());
		Date eventTime = c.getTime();
		c.add(Calendar.SECOND, 66);
		Date timestamp = c.getTime();
		boolean addCardUsage = service.addCardUsage(device,card,eventTime,timestamp);
		if (addCardUsage) {
			info("操作成功");
		}else{
			info("操作失败");
		}
	}

	/**
	 * @param msg 
	 * 
	 */
	public void info(String msg) {
		MessageBox box = new MessageBox(shell);
		box.setMessage(msg);
		box.open();
	}

	private void init() {
		if (readFile()!=null) {
			config=(DatabaseConfig) readFile();
		}
	}
	
	public Object readFile(){
		String fileName="config.temp";
		File file = new File(fileName);
		if (!file.exists()) {
			return null;
		}
		try(ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file))) {
			return ois.readObject();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	

	protected void filterCard() {
		if (allCard==null) {
			return;
		}
		String cardIdentifier = txt_cardIdentifier.getText();
		String cardSeriNumber = txt_cardSeriNumber.getText();
		String userIdentifier = txt_userIdentifier.getText();
		String userName = txt_userName.getText();
		List<PhysicalCard> list = allCard.stream().filter(new Predicate<PhysicalCard>() {
			@Override
			public boolean test(PhysicalCard t) {
				boolean checkCi=true;
				boolean checkCs=true;
				boolean checkUi=true;
				boolean checkUn=true;
				
				if (!isEmpty(cardIdentifier)) {
					checkCi=t.getIdentifier().contains(cardIdentifier);
				}
				if (!isEmpty(cardSeriNumber)) {
					checkCs=t.getSerilNumber().contains(cardSeriNumber);
				}
				if (!isEmpty(userIdentifier)) {
					checkUi=t.getUserIdentifier().contains(userIdentifier);
				}
				if (!isEmpty(userName)) {
					checkUn=t.getUserName().contains(userName);
				}
				
				return checkCi&&checkCs&&checkUi&&checkUn;
			}
		}).collect(Collectors.toList());
		fillCardTable(list);
	}
	public boolean isEmpty(String s){
		return s==null||s.trim().isEmpty();
	}

	protected void refresh() {
		service = new DataService(config);
		allDevice = service.findAllDevice();
		table.removeAll();
		for (Device device : allDevice) {
			TableItem tableItem = new TableItem(table, SWT.NONE);
			tableItem.setText(new String[]{device.getIdentifier(),device.getName(),device.getAddress(),device.getLinkAddress()});
		}
		allCard = service.findAllCard();
		mapCard = new HashMap<>();
		for (PhysicalCard physicalCard : allCard) {
			mapCard.put(physicalCard.getIdentifier(), physicalCard);
		}
		fillCardTable(allCard);
	}

	private void fillCardTable(List<PhysicalCard> allCard) {
		tb_card.removeAll();
		for (PhysicalCard physicalCard : allCard) {
			TableItem tableItem = new TableItem(tb_card, SWT.NONE);
			tableItem.setText(new String[]{physicalCard.getIdentifier(),physicalCard.getSerilNumber(),physicalCard.getUserIdentifier(),physicalCard.getUserName(),physicalCard.getUserGroup()});
		}
	}
}
